package cn.edu.scau.cmi.mazhuanglong.comprehensive;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
import javax.swing.JDesktopPane;
import java.awt.Dimension;
import javax.swing.JLabel;
import java.awt.Rectangle;
import java.awt.Component;
import java.awt.Font;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.text.NumberFormat;
import java.util.List;

import javafx.scene.input.*;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import java.awt.*;

public class teacherInterface extends JFrame implements Serializable {

	private JComboBox comboBox;
	private JComboBox comboBox_1;
	private JComboBox comboBox_2;
	private JPanel contentPane;
	public static JTable table;
	public static JScrollPane scrollpane;
	private static JTable table_1;
	private StringBuffer c = new StringBuffer();
	private char txt;
	
	String[] a = new String[] { "\u5B66\u53F7", "\u59D3\u540D", "\u5E73\u65F6\u6210\u7EE9", "\u671F\u672B\u6210\u7EE9",
			"\u603B\u8BC4" };

	double[] Score = new double[30];
	int[] n = new int[5];
//	public static Object[][] obj;
	private static int i = 0;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {

				try {

					teacherInterface frame = new teacherInterface();
					frame.setVisible(true);

				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		});
	}

	public void toSave() throws ClassNotFoundException, IOException

	{

		ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("txt.dat"));
		for (int i = 0; i < 30; i++) {
			for (int j = 0; j < 5; j++) {
				output.writeObject(table.getValueAt(i, j));

			}
		}
		toCheck();
		JOptionPane.showMessageDialog(this, "保存成功！");

	}

	/**
	 * Create the frame.
	 * 
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public teacherInterface() throws ClassNotFoundException, IOException {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 650, 900);
		contentPane = new JPanel();
		contentPane.setFont(new Font("宋体", Font.PLAIN, 20));
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);

		JPanel panel = new JPanel();
		panel.setFont(new Font("宋体", Font.PLAIN, 20));
		panel.setPreferredSize(new Dimension(10, 140));
		contentPane.add(panel, BorderLayout.NORTH);
		panel.setLayout(null);

		JLabel lblNewLabel = new JLabel("期末成绩单");
		lblNewLabel.setFont(new Font("宋体", Font.PLAIN, 20));
		lblNewLabel.setBounds(191, 13, 128, 30);
		panel.add(lblNewLabel);

		JLabel lblNewLabel_1 = new JLabel("课程:");
		lblNewLabel_1.setFont(new Font("宋体", Font.PLAIN, 16));
		lblNewLabel_1.setBounds(14, 50, 72, 18);
		panel.add(lblNewLabel_1);

		JLabel lblNewLabel_3 = new JLabel("老师:");
		lblNewLabel_3.setFont(new Font("宋体", Font.PLAIN, 16));
		lblNewLabel_3.setBounds(14, 81, 72, 18);
		panel.add(lblNewLabel_3);

		JLabel lblNewLabel_5 = new JLabel("班级:");
		lblNewLabel_5.setFont(new Font("宋体", Font.PLAIN, 16));
		lblNewLabel_5.setBounds(14, 112, 72, 18);
		panel.add(lblNewLabel_5);

		comboBox = new JComboBox();
		comboBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				comboBox.getSelectedItem();
			}
		});
		comboBox.setModel(new DefaultComboBoxModel(new String[] { "肖磊", "钟存" }));
		comboBox.setBounds(191, 79, 128, 24);
		panel.add(comboBox);

		comboBox_1 = new JComboBox();
		comboBox_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				comboBox_1.getSelectedItem();
			}
		});
		comboBox_1.setModel(new DefaultComboBoxModel(new String[] { "2017级软件工程1班", "2017级软件工程2班" }));
		comboBox_1.setBounds(191, 110, 165, 24);
		panel.add(comboBox_1);

		comboBox_2 = new JComboBox();
		comboBox_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {

				comboBox_2.getSelectedItem();
			}
		});

		comboBox_2.setModel(new DefaultComboBoxModel(new String[] { "面对对象程序设计", "大学英语" }));
		comboBox_2.setBounds(191, 48, 165, 24);
		panel.add(comboBox_2);

		JPanel panel_1 = new JPanel();
		panel_1.setMaximumSize(new Dimension(32767, 200));
		panel_1.setPreferredSize(new Dimension(10, 300));
		contentPane.add(panel_1, BorderLayout.CENTER);
		panel_1.setLayout(null);
		if (comboBox_1.getSelectedItem()=="2017级软件工程1班") {
			table = new JTable(new MyTableModel() {
				@Override
				public boolean isCellEditable(int rowIndex, int columnIndex) {
					return columnIndex != 4;

				}

				@Override
				public Object getValueAt(int rowIndex, int columnIndex) {
					return obj[rowIndex][columnIndex];
				}

				@Override
				public void setValueAt(Object newValue, int rowIndex, int columnIndex) {
					// 设置新的单元格数据时，必须把新值设置到原数据数值中，
					// 待更新UI重新调用 getValueAt(...) 获取单元格值时才能获取到最新值
					obj[rowIndex][columnIndex] = newValue;
					// 设置完数据后，必须通知表格去更新UI（重绘单元格），否则显示的数据不会改变
					fireTableCellUpdated(rowIndex, columnIndex);
				}

			});
		}
		if (comboBox_1.getSelectedItem()=="2017级软件工程2班") {
			table = new JTable(new MyTableModel2() {
				@Override
				public boolean isCellEditable(int rowIndex, int columnIndex) {
					return columnIndex != 4;

				}

				@Override
				public Object getValueAt(int rowIndex, int columnIndex) {
					return obj[rowIndex][columnIndex];
				}

				@Override
				public void setValueAt(Object newValue, int rowIndex, int columnIndex) {
					// 设置新的单元格数据时，必须把新值设置到原数据数值中，
					// 待更新UI重新调用 getValueAt(...) 获取单元格值时才能获取到最新值
					obj[rowIndex][columnIndex] = newValue;
					// 设置完数据后，必须通知表格去更新UI（重绘单元格），否则显示的数据不会改变
					fireTableCellUpdated(rowIndex, columnIndex);
				}

			});
		}
		JScrollPane sp = new JScrollPane(table);

		getContentPane().add(sp);
		table.setRowHeight(30);

		final TableModel tablemodel = table.getModel();
		tablemodel.addTableModelListener(new TableModelListener() {
			public void tableChanged(TableModelEvent e) {
				int firstRow = e.getFirstRow();// 第一个改变的行数
				int lastRow = e.getLastRow();// 最后个改变的行数

				int column = e.getColumn();// 改变的列数

				int type = e.getType();// 获取数据改变类型

				if (type == TableModelEvent.UPDATE) {
					if (column > 3) {
						return;
					}

					for (int row = firstRow; row <= lastRow; row++) {
						Object pingshiObj = tablemodel.getValueAt(row, 2);
						Object qimoObj = tablemodel.getValueAt(row, 3);

						int pingshi = 0;
						try {
							pingshi = Integer.parseInt("" + pingshiObj);

						} catch (Exception ex) {
							ex.printStackTrace();
						}
						int qimo = 0;
						try {
							qimo = Integer.parseInt("" + qimoObj);

						} catch (Exception ex) {
							ex.printStackTrace();
						}

						double totalScore = (double) pingshi / 2 + (double) qimo / 2;
						if (totalScore < 0)
							totalScore = 0;
						NumberFormat nf = NumberFormat.getNumberInstance();
						nf.setMaximumFractionDigits(2);

						tablemodel.setValueAt(nf.format(totalScore), row, 4);

					}

				}
			}
		});

		// 创建单元格编辑器，使用文本框作为编辑组件
		MyCellEditor cellEditor = new MyCellEditor(new JTextField());

		// 遍历表格中所有数字列，并设置列单元格的编辑器
		for (int i = 1; i < a.length; i++) {
			if (i != 1) {
				// 根据 列名 获取 表格列
				TableColumn tableColumn = table.getColumn(a[i]);
				// 设置 表格列 的 单元格编辑器
				tableColumn.setCellEditor(cellEditor);
			}
		}

		// 使用 表格模型 创建 行排序器（TableRowSorter 实现了 RowSorter）
		RowSorter<TableModel> rowSorter = new TableRowSorter<TableModel>(tablemodel);

		// 给 表格 设置 行排序器
		table.setRowSorter(rowSorter);

		JPanel panel_2 = new JPanel();
		panel_2.setPreferredSize(new Dimension(10, 300));
		contentPane.add(panel_2, BorderLayout.SOUTH);

		JButton btnNewButton = new JButton("保存");
		btnNewButton.setBounds(464, 112, 113, 27);
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					toSave();
				} catch (ClassNotFoundException | IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		panel_2.setLayout(null);
		panel_2.add(btnNewButton);

		JButton btnNewButton_1 = new JButton("关闭\r\n");
		btnNewButton_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				toClose();
			}
		});
		btnNewButton_1.setBounds(464, 152, 113, 27);
		panel_2.add(btnNewButton_1);

		Object[] columnNames2 = { "成绩区段", "人数", "百分比" };

		Object[][] rowData = new Object[6][3];

		for (int i = 0; i < table.getRowCount(); i++) {
			Score[i] = new Double(tablemodel.getValueAt(i, 4).toString());
			if (Score[i] < 60)
				n[4]++;
			if (Score[i] >= 60 && Score[i] < 70)
				n[3]++;
			if (Score[i] >= 70 && Score[i] < 80)
				n[2]++;
			if (Score[i] >= 80 && Score[i] < 90)
				n[1]++;
			if (Score[i] >= 90 && Score[i] <= 100)
				n[0]++;
		}
		NumberFormat nf = NumberFormat.getNumberInstance();
		nf.setMaximumFractionDigits(2);
		for (int i = 0; i < 6; i++) {
			switch (i) {
			case 0:
				rowData[i][0] = "成绩区段";
				rowData[i][1] = "人数";
				rowData[i][2] = "百分比";
				break;
			case 1:
				rowData[i][0] = "90-100";
				rowData[i][1] = n[i - 1];
				rowData[i][2] = nf.format((double) n[i - 1] / 30);
				break;
			case 2:
				rowData[i][0] = "80-89";
				rowData[i][1] = n[i - 1];
				rowData[i][2] = nf.format((double) n[i - 1] / 30);
				break;
			case 3:
				rowData[i][0] = "70-79";
				rowData[i][1] = n[i - 1];
				rowData[i][2] = nf.format((double) n[i - 1] / 30);
				break;
			case 4:
				rowData[i][0] = "60-69";
				rowData[i][1] = n[i - 1];
				rowData[i][2] = nf.format((double) n[i - 1] / 30);
				break;
			case 5:
				rowData[i][0] = "0-59";
				rowData[i][1] = n[i - 1];
				rowData[i][2] = nf.format((double) n[i - 1] / 30);
				break;
			}
		}
		table_1 = new JTable(new ScoreTableModel() {
			@Override
			public boolean isCellEditable(int rowIndex, int columnIndex) {
				return false;

			}

			@Override
			public Object getValueAt(int rowIndex, int columnIndex) {
				return rowData[rowIndex][columnIndex];
			}

			@Override
			public void setValueAt(Object newValue, int rowIndex, int columnIndex) {
				// 设置新的单元格数据时，必须把新值设置到原数据数值中，
				// 待更新UI重新调用 getValueAt(...) 获取单元格值时才能获取到最新值
				rowData[rowIndex][columnIndex] = newValue;
				// 设置完数据后，必须通知表格去更新UI（重绘单元格），否则显示的数据不会改变
				fireTableCellUpdated(rowIndex, columnIndex);
			}

		});

		table_1.setBounds(14, 13, 308, 240);

		table_1.setRowHeight(40);// 设置表格高度
		panel_2.add(table_1);

		this.setLocationRelativeTo(null);// 窗体居中函数
		this.setTitle("成绩单");
	}

	protected void toClose() {
		this.dispose();
	}

	public void toCheck() {
		n = new int[5];
		for (int i = 0; i < table.getRowCount(); i++) {
			Score[i] = new Double(table.getValueAt(i, 4).toString());
			if (Score[i] < 60)
				n[4]++;
			if (Score[i] >= 60 && Score[i] < 70)
				n[3]++;
			if (Score[i] >= 70 && Score[i] < 80)
				n[2]++;
			if (Score[i] >= 80 && Score[i] < 90)
				n[1]++;
			if (Score[i] >= 90 && Score[i] <= 100)
				n[0]++;
		}
		NumberFormat nf = NumberFormat.getNumberInstance();
		nf.setMaximumFractionDigits(2);
		for (int i = 1; i < 6; i++) {
			table_1.setValueAt(n[i - 1], i, 1);
			table_1.setValueAt(nf.format((double) n[i - 1] / 30), i, 2);

		}
//		table_1.repaint();
	}
}
